package comHttp

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"io/ioutil"
	"net/http"
)

type MT string

const (
	Get    MT = "GET"
	Post      = "POST"
	Put       = "PUT"
	Patch     = "PATCH"
	Delete    = "DELETE"
)

func (mt MT) String() string {
	return string(mt)
}
func Request[T any](url string, httpMethod MT, data interface{}) (T, error) {
	var (
		backData T
	)
	marshal, err := json.Marshal(data)
	if err != nil {
		return backData, err
	}
	client := &http.Client{}
	req, err := http.NewRequest(httpMethod.String(), url, bytes.NewBuffer(marshal))
	if err != nil {
		fmt.Println("Error:", err)
		return backData, err
	}
	req.Header.Set("Content-Type", "application/json")

	resp, err := client.Do(req)
	if err != nil {
		fmt.Println("Error:", err)
		return backData, err
	}
	defer func(Body io.ReadCloser) {
		err := Body.Close()
		if err != nil {

		}
	}(resp.Body)

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Println("Error:", err)
		return backData, err
	}
	fmt.Println(string(body))
	err = json.Unmarshal(body, &backData)
	return backData, nil
}
